package com.bluemsun.naturallanguageprocessing.Aspect;

import com.bluemsun.naturallanguageprocessing.common.ExceptionEnum;
import com.bluemsun.naturallanguageprocessing.common.ServerResponse;
import com.bluemsun.naturallanguageprocessing.dao.CollectionMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.lang.annotation.Retention;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Aspect
@Component
public class CollectAop {

    @Resource
    private CollectionMapper collectionMapper;

    private static final Logger logger = LoggerFactory.getLogger(CollectAop.class);

    @Pointcut("@annotation(com.bluemsun.naturallanguageprocessing.Aspect.annotation.IsUserOfFavorite)")
    public void pointCut(){
    }

    @Before("pointCut()")
    public void IsUserOfFavorite(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        Integer userId = (Integer) args[0];
        Set<Integer> favoriteIds = null;
        if (args[1].getClass() == Integer.class){
            favoriteIds = new HashSet<>();
            favoriteIds.add((Integer) args[1]);
        }else if (args[1].getClass() == HashSet.class){
             favoriteIds = (HashSet<Integer>) args[1];
        }else {
            throw new RuntimeException("参数类型无法匹配");
        }
        Integer hasFavorite = null;
        Integer favoriteId = null;
        try{
            // 先判断用户是否有这个收藏夹
            for (Iterator<Integer> iterator = favoriteIds.iterator();iterator.hasNext();){
                hasFavorite = collectionMapper.hasFavorite(userId, iterator.next());
                if (hasFavorite == null) {
                    // 表示用户没有这个收藏夹
                    logger.error("数据库里面没有查询到ID为用户的收藏,该用户ID为{},收藏夹ID为{}",userId,favoriteId);
                    throw new RuntimeException("某个收藏夹不存在");
                }else if (hasFavorite != 1) {
                    logger.error("数据库用户与收藏夹关系表数据异常,用户ID为{},收藏夹ID为{},用户与收藏夹出现重复关系",userId,favoriteId);
                    throw new RuntimeException(ExceptionEnum.CANNOT_EXCEPTION.getMsg());
                }
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }
}
